<?php
// +----------------------------------------------------------------------
// | MEAdmin [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2020 http://www.meetes.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 扯文艺的猿 <meetes@163.com>
// +----------------------------------------------------------------------

namespace app\common\controller;
use ApiSafety\SafetyFactory;
use think\helper\Hash;

/**
 * Api接口公共控制器
 * @package app\common\controller
 */
class Api extends Common
{
    protected $key;
    protected $appid;
    protected $appsecret;

    public function initialize()
    {
        $config = config('key.');
        $this->key = $config['key'];
        $this->appid = $config['appid'];
        $this->appsecret = $config['appsecret'];
    }

    /**
     * 校验数据可用性
     * @param array $data 数据
     * @return bool|array
     */
    public static function decodeData(&$data = [])
    {
        if (empty($data)) return false;   //参数不能为空

        $config = config('key.');
        $KEY = $config['key'];
        $APPID = $config['appid'];
        $APPSECRET = $config['appsecret'];

        // 1.校验临时票据是否过期
        if (isset($data['jsapi_ticket'])) {
            $jsapi_ticket = $data['jsapi_ticket'];
            if (empty($jsapi_ticket)) return false;

            $JwtObj = SafetyFactory::factory('Jwt', $KEY);
            $JwtResult = $JwtObj->verifyToken($jsapi_ticket);
            if ($JwtResult == false) {
                return false;
                // return ['code'=>-4,'message'=>'凭证错误!'];
            }
        }

        // 2.校验 account_token 是否正确
        if (isset($jsapi_ticket['jti'])) {
            $accessToken = $jsapi_ticket['jti'];
            if (empty($accessToken)) return false;

            if (!Hash::check($APPID . $APPSECRET, base64_decode($accessToken) )) {
                return false;
                // return ['code'=>-5,'message'=>'密钥不匹配!'];
            }
        }
        // 3.校验签名是否过期
        if (isset($data['signature']) && isset($data['timestamp']) && isset($data['appid'])) {
            $signature = $data['signature'];
            if (empty($signature)) return false;
            
            $SignObj = SafetyFactory::factory('Sign', $KEY);
            $SignResult = $SignObj->getSign($data);
            
            if ($SignResult != $signature) {
                return false;
            }

            if ($data['timestamp'] + 60 < time() || $data['appid'] != $APPID) {
                return false;
            }

            // 过滤参数
            unset($data['appid'], $data['timestamp'], $data['signature'], $data['jsapi_ticket'], $data['noncestr']);
            return true;
        }
        return false;
    }


    /**
     * 加密数据返回接口
     * @param array $data 数据
     * @return bool
     */
    public static function encodeData($data = [])
    {
        if (empty($data)) return false;   //参数不能为空

        $config = config('key.');
        $KEY = $config['key'];
        $APPID = $config['appid'];
        $APPSECRET = $config['appsecret'];
        
        // 1.生成 account_token 账号凭证
        $accessToken = base64_encode( Hash::make($APPID . $APPSECRET) );

        // 2.利用 账号凭证 生成临时票据
        $tokenArr = [
            'iss' => 'lingfu',
            'exp' => strtotime(date('Y-m-d 24:0:0', time())), //time()+7200
            'jti' => $accessToken,
        ];
        $JwtObj = SafetyFactory::factory('Jwt', $KEY);
        $data['jsapi_ticket'] = $JwtObj->getToken($tokenArr);

        // 3.利用临时票据，生成签名
        $data['appid']      = $APPID;
        $data['noncestr']   = random_string(10);
        $data['timestamp']  = time();
        $SignObj = SafetyFactory::factory('Sign', $KEY);
        $data['signature']  = $SignObj->getSign($data);

        // 4.返回数据
        return $data;
    }
        
}
